<template>
  <div class="app-container table-app-container">
    <div class="fixed-table">
      <div class="fixed-table-actionbar" style="display: flex; justify-content: space-between;">
        <div>
          <span>属性变更</span>
        </div>
        <ActionBar v-if="!view" :instance-id="instanceId" @addRow="addRow" />
      </div>

      <PageableTable
        v-if="isRouterAlive"
        ref="table"
        :loading="false"
        :data="tableData"
        :table-height="200"
        :row-class-name="tableRowClassName"
        :disable-pageable="true"
        :multiple-selected="false"
        class="fixed-table-table"
      >
        <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :sortable="column.sortable">
          <template slot-scope="scope">
            <column-render :render="column.render" :row="scope.row" :column="column" />
          </template>
        </el-table-column>
        <el-table-column v-if="!view" label="变更后">
          <template slot-scope="scope">
            <string-input v-model="scope.row.afterChange" style="display: inline-block;" />
            <!-- <bool-checkbox v-if="getAttrDType(scope.row.key) === 'bool'" v-model="scope.row.afterChange" style="display: inline-block;" />
            <number-input v-if="getAttrDType(scope.row.key) === 'number'" v-model="scope.row.afterChange" style="display: inline-block; max-width: 200px;" />
            <enum-select v-if="getAttrDType(scope.row.key) === 'enum'" v-model="scope.row.afterChange" :options="getEnmuOptions(scope.row.key)" style="display: inline-block;" />
            <foreign-select
              v-if="getAttrDType(scope.row.key) === 'foreign'"
              v-model="scope.row.afterChange"
              :schema="getForeignKey(scope.row.key)"
              :width="200"
              style="display: inline-block;"
            />
            <datasource-select
              v-if="getAttrDType(scope.row.key) === 'datasource'"
              v-model="scope.row.afterChange"
              :options="getEnmuOptions(scope.row.key)"
              :url="getDatasource(scope.row.key).url"
              :value-key="getDatasource(scope.row.key).valueKey"
              :label-key="getDatasource(scope.row.key).labelKey"
              :response-key="getDatasource(scope.row.key).responseKey"
              :width="200"
              style="display: inline-block;"
            /> -->
          </template>
        </el-table-column>
        <el-table-column v-if="view" label="变更后">
          <template slot-scope="scope">
            {{ scope.row.afterChange }}
            <!-- <span v-if="getAttrDType(scope.row.key) !== 'foreign'">{{ getAttrValue(scope.row.key, scope.row.afterChange) }}</span> -->
            <!-- <foreign-select v-if="getAttrDType(scope.row.key) === 'foreign'" v-model="scope.row.afterChange" :disabled="true" :schema="getForeignKey(scope.row.key)" :width="150" /> -->
          </template>
        </el-table-column>
        <el-table-column v-if="!view" label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button title="取消选择" type="text" size="mini" icon="el-icon-back" @click="onCancelProperty(row)" />
          </template>
        </el-table-column>
      </PageableTable>
    </div>
  </div>
</template>

<script>
import ActionBar from './components/actionBar'
import PageableTable from '@neu/biz-core/components/PageableTable'
import databind from '@neu/biz-core/mixins/databind'
import { deepClone, parseTime } from '@neu/biz-core/utils'
import { detail as schemaDetail } from '@neu/dcom-ui/api/schema'
import { detail as instanceDetail } from '@neu/dcom-ui/api/instance'

export default {
  name: 'ChangeCiPropertyPage',
  components: {
    ActionBar,
    PageableTable
  },
  // 加入混入，使表格混入更多的api操作
  mixins: [databind],
  props: {
    multipleSelected: {
      type: Boolean,
      default: false
    },
    instanceId: {
      required: true,
      type: String,
      default: ''
    },
    view: {
      required: false,
      type: Boolean
    },
    propertyData: {
      required: false,
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      instance: {
        name: '',
        schemadef: {
          _id: '',
          name: ''
        },
        attrs: {}
      },
      schemaAttrs: [],
      insideColumns: [
        {
          title: '属性名称',
          key: 'name'
        },
        {
          title: '变更前',
          key: 'value'
        }
      ],
      tableData: [],
      isRouterAlive: true
    }
  },
  watch: {
    propertyData: {
      handler(newVal, oldVal) {
        this.tableData = this.propertyData
      },
      immediate: true
    },
    instanceId: {
      handler(newVal, oldVal) {
        this.fetch()
      },
      immediate: true
    }
  },
  created() {
    this.fetch()
  },
  methods: {
    // 获取实例详细信息
    fetch: function() {
      if (this.instanceId === '') {
        return
      }
      this.requestLoading = true
      // instanceDetail(this.instanceId).then(response => {
      //   const data = response.data
      //   this.tableData = Object.entries(deepClone(data)).map(e => {return {name: e[0], value: e[1]}})
      //   return
      //   const _attrs = response.data.attrs
      //   const attrs = _attrs.reduce((o, item) => { o[item.key] = item.value; return o }, {})
      //   this.cloneAttrs = deepClone(attrs)

      //   schemaDetail(response.data.schemadef._id).then(response2 => {
      //     const instance = { ...response.data, attrs, schemadef: response2.data }
      //     this.instance = instance
      //     let schemaAttrs = response2.data.attrs
      //     const categoryAttrs = response2.data.category.attrs || []
      //     schemaAttrs = [...schemaAttrs, ...categoryAttrs]

      //     this.schemaAttrs = Object.freeze(schemaAttrs)
      //     this.requestLoading = false
      //   })
      // })
    },

    // 撤销选择已有关系，删除DCOM保存的数据
    onCancelProperty(row) {
      this.$confirm('撤销选择当前实例属性?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData.splice(row.index, 1)
        this.$message({
          type: 'success',
          message: '撤销成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    // 设置行索引
    tableRowClassName({ row, rowIndex }) {
      row.index = rowIndex
    },

    addRow(row) {
      if (this.tableData == null) {
        this.tableData = []
      }
      const keyArray = []
      for (let i = 0; i < this.tableData.length; i++) {
        keyArray.push(this.tableData[i].key)
      }

      for (let i = 0; i < row.length; i++) {
        if (!keyArray.includes(row[i].key)) {
          this.tableData.push(row[i])
        }
      }
    },
    // 表格刷新
    reload() {
      this.isRouterAlive = false
      this.$nextTick(function() {
        this.isRouterAlive = true
      })
    },

    // 获取属性的数据类型定义
    getAttrDType(k) {
      const schemaAttr = this.schemaAttrs.find(it => it.field === k)
      return schemaAttr ? schemaAttr.dtype : 'string'
    },

    // 获取枚举属性的枚举项定义
    getEnmuOptions(k) {
      const schemaAttr = this.schemaAttrs.find(it => it.field === k)
      return schemaAttr ? schemaAttr.enums : []
    },

    // 获取数据源属性的数据源定义
    getDatasource(k) {
      const schemaAttr = this.schemaAttrs.find(it => it.field === k)
      return schemaAttr ? schemaAttr.datasource : {}
    },

    // 获取格式化属性值
    getAttrValue(k, v) {
      const attr = this.schemaAttrs.find(it => it.field === k)
      if (attr.dtype === 'date') {
        return parseTime(v)
      } else if (attr.dtype === 'enum') {
        const enumItem = attr.enums.find(e => e.value === v)
        return enumItem ? enumItem.label : ''
      } else if (attr.dtype === 'bool') {
        return v ? '是' : '否'
      }
      return v !== null ? v : '未设置'
    },

    // 获取外键属性的定义
    getForeignKey(k) {
      const schemaAttr = this.schemaAttrs.find(it => it.field === k)
      return schemaAttr ? schemaAttr.dvalue : ''
    }
  }
}
</script>
